require('../../util/util.js');
const _util = require('../../util/util.js');
var _cart_service = require('../../service/cart-service.js');
var _header = require('page/common/header/index.js');
var listTemplate = require('./index.string');
const { groupBy } = require('lodash');

var cartList = {
    listData: {
        headList: [],
        itemList: {},
        totalPrice: {},
        total:''
    },
    itemHeadList: [
        'Item ID',
        'Product ID',
        'Description',
        'Instock',
        'Quantity',
        'List Price',
        'Total Cost',
        '',
    ],
    init: function () {
        this.bindEvents();
        this.loadCartList();
        return this;
    },
    bindEvents: function () {
        var _this = this;

        $(document).delegate('.number', 'blur', function () {
            if(this.value > 0){
                _this.updateNum(this.name, this.value);
                }
            else if(this.value == 0){
                    _cart_service.removeItem(this.name, 
                        function(res){
                            window.location.href = _util.getURLParam('redirect') || './cart.html';
                        }, function(errMsg){console.log(errMsg)});
                }
                else {
                    alert("请输入正整数");
                };
        });

        $(document).delegate('.remove','click',function(){
            _cart_service.removeItem(this.name, 
                function(res){
                    console.log(this.name);
                    window.location.href = _util.getURLParam('redirect') || './cart.html';
                }, function(errMsg){console.log(errMsg)});
        });
    },
    updateNum: function (itemId, quantity) {
        _cart_service.updateNum(quantity, itemId, function(res){
            window.location.href = _util.getURLParam('redirect') || './cart.html';

        }, function(){

        });
    },
    loadCartList: function () {
        var _this = this;      
        _cart_service.viewCart(
            function (res) {
                _this.listData.headList = _this.itemHeadList;
                _this.listData.itemList = res;
                if(!(_this.listData.itemList == "购物车为空"))
                {   
                    _cart_service.getCartTotal(
                        function(res){
                            _this.listData.total = res;
                        },
                        function(){}
                    );
                    var result = _util.renderHtml(listTemplate, { ListData: _this.listData });
                    $('#Catalog').html(result);
                    $('#cartEmptyMsg').hide();
                }else{
                    $('#cartEmptyMsg').show();
                }
            },
            function (errMsg) {
                $('#cartEmptyMsg').show();
            }
        );
    },
   
};

module.exports = cartList.init();